var departmentFun = function (options) {
	this.options = {
		regions: null,
		departments: null,
		salers: null,
		container: '#department',
		where: {
			region_id: 0,
			department_id: 0,
			saler_id:0
		},
	};

	$.extend(true, this.options, options);

	this.select = function(data, prepend, selected) {
		var temp = new Array();
		var value = '';
		if (prepend) {
			for(var key in prepend) {
				if (selected && selected == key) {
					value = '<option value="'+ key +'" selected>' + prepend[key] + '</option>';
				} else {
					value = '<option value="'+ key +'">' + prepend[key] + '</option>';
				}
				temp.push(value);
			}
		}
		if (data) {
			for(var i in data) {
				if (selected && data[i].id == selected) {
					value = '<option value="'+ data[i].id +'" selected>' + data[i].name + '</option>';
				} else {
					value = '<option value="'+ data[i].id +'">' + data[i].name + '</option>';
				}
				temp.push(value);
			}
		}

		return temp.join('');
	};

	this.make = function() {
		// console.log(this.options);
		var _this  = this;
		var container = $(this.options.container);
		var where = this.options.where;

		// 区域
		if (this.options.regions) {  
			$(container).find('.region').html(this.select(this.options.departments, {0:'请选择区域'}, where.region_id));
		}

		// 部门
		if ($(container).find('.department').length > 0) {
			if (where.region_id > 0) {
				$(container).find('.department').html(this.select(this.options.departments[where.region_id].children, {0:'请选择部门'}, where.department_id));
			} else {
				$(container).find('.department').html(this.select(null, {0:'请选择部门'}));
			}
		}

		// 业务员
		if ($(container).find('.saler').length > 0) {
			$(container).find('.saler').html(this.select(this.options.salers[where.department_id], {0:'请选择业务员'}, where.saler_id || 0));
		}

		$(container).find('.region').change(function() {
			if ($(this).val() > 0) {
				$(container).find('.department').html(_this.select(_this.options.departments[Number($(this).val())].children, {0:'请选择部门'}));
			} else {
				$(container).find('.department').html(_this.select(null, {0:'请选择部门'}));
			}
		});

		$(container).find('.department').change(function() {
			return $(container).find('.saler').length && $(container).find('.saler').html(_this.select(_this.options.salers[$(this).val()], {0:'请选择业务员'}));
		});
	};
};

window.department = {
	init: function(options) {
		return new departmentFun(options);
	}
};